import axios from "axios";
import { ElMessage } from "element-plus/es";
import db from "./db";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000,
});

service.interceptors.request.use(
  (config) => {
    const token = db.get("token");
    if (!config.url.startsWith("/api/login")) {
      config.headers.common["Authorization"] = `Bearer ${token}`;
    }

    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return response.data;
    } else {
      return Promise.reject(new Error(response.data.message || "Error"));
    }
  },
  (error) => {
    ElMessage.error(error.response.data.message);
    return Promise.reject(error);
  }
);

export default service;
